{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "authorship_tag": "ABX9TyMQMnzD1ZmFkrax2yUbuaNc",
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/sugarforever/wtf-langchain/blob/main/07_Memory/07_Memory.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "\n",
        "os.environ['OPENAI_API_KEY'] = ''"
      ],
      "metadata": {
        "id": "_b-_WhYBeEJO"
      },
      "execution_count": 1,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "xlgJ4rFm-CS6",
        "outputId": "288377e7-39d0-43e3-c133-76528dc66f3d"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.3/1.3 MB\u001b[0m \u001b[31m10.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m90.0/90.0 kB\u001b[0m \u001b[31m9.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m3.1/3.1 MB\u001b[0m \u001b[31m21.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m49.4/49.4 kB\u001b[0m \u001b[31m5.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h"
          ]
        }
      ],
      "source": [
        "!pip install langchain==0.0.235 --quiet"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from langchain.memory import ConversationBufferMemory"
      ],
      "metadata": {
        "id": "1ILWDRoJ-NmX"
      },
      "execution_count": 3,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "memory = ConversationBufferMemory()\n",
        "memory.save_context({\"input\": \"hi\"}, {\"output\": \"whats up\"})"
      ],
      "metadata": {
        "id": "Blhn900A-SI9"
      },
      "execution_count": 4,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "memory.chat_memory.messages"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "gcsHB8Fa_fpq",
        "outputId": "635f1dd6-9c2e-4e0c-aeba-7b77c99f4176"
      },
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[HumanMessage(content='hi', additional_kwargs={}, example=False),\n",
              " AIMessage(content='whats up', additional_kwargs={}, example=False)]"
            ]
          },
          "metadata": {},
          "execution_count": 5
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "memory.load_memory_variables({})"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "dz-T1nKS-Wa8",
        "outputId": "ca78781f-bcbb-4d9e-97df-a189e2e2e43f"
      },
      "execution_count": 6,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'history': 'Human: hi\\nAI: whats up'}"
            ]
          },
          "metadata": {},
          "execution_count": 6
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "memory = ConversationBufferMemory(return_messages=True)\n",
        "memory.save_context({\"input\": \"hi\"}, {\"output\": \"whats up\"})"
      ],
      "metadata": {
        "id": "FDXjUwRk-YkS"
      },
      "execution_count": 7,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "memory.load_memory_variables({})"
      ],
      "metadata": {
        "id": "9xbrG4Vm-cnG"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "from langchain.memory import ConversationBufferWindowMemory"
      ],
      "metadata": {
        "id": "qkJ4tGlGCOgm"
      },
      "execution_count": 8,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "memory = ConversationBufferWindowMemory( k=1)\n",
        "memory.save_context({\"input\": \"Hi, LangChain!\"}, {\"output\": \"Hey!\"})\n",
        "memory.save_context({\"input\": \"Where are you?\"}, {\"output\": \"By your side\"})"
      ],
      "metadata": {
        "id": "vMuMG8yzCRDE"
      },
      "execution_count": 9,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "memory.load_memory_variables({})"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "lDSZ8psOCUgn",
        "outputId": "654dc0e9-5d7b-4b58-8ca2-8124ae5d3006"
      },
      "execution_count": 10,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'history': 'Human: Where are you?\\nAI: By your side'}"
            ]
          },
          "metadata": {},
          "execution_count": 10
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "memory.chat_memory.messages"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "GDSbCvruCWOb",
        "outputId": "fc570f38-bcc9-4cff-806b-c463041d6477"
      },
      "execution_count": 11,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[HumanMessage(content='Hi, LangChain!', additional_kwargs={}, example=False),\n",
              " AIMessage(content='Hey!', additional_kwargs={}, example=False),\n",
              " HumanMessage(content='Where are you?', additional_kwargs={}, example=False),\n",
              " AIMessage(content='By your side', additional_kwargs={}, example=False)]"
            ]
          },
          "metadata": {},
          "execution_count": 11
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install openai"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "mSH0l-K6vDjW",
        "outputId": "3a5c5ebb-c350-40c7-e99c-8736f2d06ae9"
      },
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Requirement already satisfied: openai in /usr/local/lib/python3.10/dist-packages (0.27.10)\n",
            "Requirement already satisfied: requests>=2.20 in /usr/local/lib/python3.10/dist-packages (from openai) (2.31.0)\n",
            "Requirement already satisfied: tqdm in /usr/local/lib/python3.10/dist-packages (from openai) (4.66.1)\n",
            "Requirement already satisfied: aiohttp in /usr/local/lib/python3.10/dist-packages (from openai) (3.8.5)\n",
            "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests>=2.20->openai) (3.2.0)\n",
            "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests>=2.20->openai) (3.4)\n",
            "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests>=2.20->openai) (2.0.4)\n",
            "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests>=2.20->openai) (2023.7.22)\n",
            "Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->openai) (23.1.0)\n",
            "Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.10/dist-packages (from aiohttp->openai) (6.0.4)\n",
            "Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /usr/local/lib/python3.10/dist-packages (from aiohttp->openai) (4.0.3)\n",
            "Requirement already satisfied: yarl<2.0,>=1.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->openai) (1.9.2)\n",
            "Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.10/dist-packages (from aiohttp->openai) (1.4.0)\n",
            "Requirement already satisfied: aiosignal>=1.1.2 in /usr/local/lib/python3.10/dist-packages (from aiohttp->openai) (1.3.1)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from langchain.memory import ConversationSummaryMemory, ChatMessageHistory\n",
        "from langchain.llms import OpenAI\n",
        "from langchain.prompts import PromptTemplate\n",
        "from langchain.chains import LLMChain\n",
        "\n",
        "template = \"\"\"You are a chatbot having a conversation with a human.\n",
        "\n",
        "{conversation_history}\n",
        "\n",
        "Human: {input}\n",
        "Chatbot:\"\"\"\n",
        "\n",
        "prompt = PromptTemplate(\n",
        "    input_variables=[\"conversation_history\", \"input\"], template=template\n",
        ")\n",
        "memory = ConversationBufferMemory(memory_key=\"conversation_history\")\n",
        "\n",
        "llm_chain = LLMChain(\n",
        "    llm=OpenAI(),\n",
        "    prompt=prompt,\n",
        "    verbose=True,\n",
        "    memory=memory,\n",
        ")"
      ],
      "metadata": {
        "id": "I6cFKiW4vISf"
      },
      "execution_count": 19,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "llm_chain.predict(input=\"Where is Paris?\")"
      ],
      "metadata": {
        "id": "HYZT0RQ1l3DF",
        "outputId": "66854d0c-3b5f-4635-c0d8-8f8130009ea9",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 256
        }
      },
      "execution_count": 20,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "\n",
            "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
            "Prompt after formatting:\n",
            "\u001b[32;1m\u001b[1;3mYou are a chatbot having a conversation with a human.\n",
            "\n",
            "\n",
            "\n",
            "Human: Where is Paris?\n",
            "Chatbot:\u001b[0m\n",
            "\n",
            "\u001b[1m> Finished chain.\u001b[0m\n"
          ]
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "' Paris is the capital and most populous city of France. It is located on the Seine River, in northern France, at the heart of the Île-de-France region.'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 20
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "llm_chain.predict(input=\"What did I just ask?\")"
      ],
      "metadata": {
        "id": "fexSvRR5l8BD",
        "outputId": "c4b9fbaa-4a1f-4b9d-9ea1-4ae22c19ffcf",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 275
        }
      },
      "execution_count": 21,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "\n",
            "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
            "Prompt after formatting:\n",
            "\u001b[32;1m\u001b[1;3mYou are a chatbot having a conversation with a human.\n",
            "\n",
            "Human: Where is Paris?\n",
            "AI:  Paris is the capital and most populous city of France. It is located on the Seine River, in northern France, at the heart of the Île-de-France region.\n",
            "\n",
            "Human: What did I just ask?\n",
            "Chatbot:\u001b[0m\n",
            "\n",
            "\u001b[1m> Finished chain.\u001b[0m\n"
          ]
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "' You asked me where Paris is.'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 21
        }
      ]
    }
  ]
}